package com.xingzhe.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@ControllerAdvice
//@RestControllerAdvice
public class GlobalExceptionHandler {
  @ResponseBody
  @ExceptionHandler(XingZhePlusException.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public RestErrorResponse customException(XingZhePlusException e){
    //记录异常
    log.error("自定义异常{}",e.getErrMessage(),e);
    //解析出异常信息
    String errMessage = e.getErrMessage();
    return new RestErrorResponse(errMessage);
  }

/*  @ResponseBody
  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public RestErrorResponse exception(Exception e){
    //记录异常
    log.error("系统异常{}",e.getMessage(),e);
    //解析出异常信息
    return  new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
  }*/


  @ResponseBody
  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public RestErrorResponse methodArgumentNotValidException(MethodArgumentNotValidException e){
    //存贮错误信息
    BindingResult bindingResult = e.getBindingResult();
    List<String> errors=new ArrayList<>();
    bindingResult.getFieldErrors().stream().forEach(item->{
      errors.add(item.getDefaultMessage());
    });

    //将list中的错误信息拼接起来
    String errMessage = StringUtils.join(errors, ",");

    //记录异常
    log.error("系统异常{}",e.getMessage(),errMessage);
    //解析出异常信息
    return  new RestErrorResponse(errMessage);
  }

  @ResponseBody
  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public RestErrorResponse exception_auth(Exception e) {

    log.error("【系统异常】{}",e.getMessage(),e);
    e.printStackTrace();
    if(e.getMessage().equals("不允许访问")){
      return new RestErrorResponse("没有操作此功能的权限");
    }
    return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
  }

}
